package com.gt.config;

import com.gt.interceptor.HttpComponentsClientRestfulHttpRequestFactory;
import com.gt.interceptor.LoggingRequestInterceptor;
import com.gt.task.RestTemplateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 构造RestTemplate
 */
@Configuration
public class RestTemplateConfig {
    @Autowired
    @Lazy
    private List<RestTemplateTask> taskList;

    @Bean
    @Primary
    public RestTemplate getRestTemplate() {
        HttpComponentsClientRestfulHttpRequestFactory httpRequestFactory = new HttpComponentsClientRestfulHttpRequestFactory();
        //服务有的服务响应时间较长，暂定2分钟
        httpRequestFactory.setReadTimeout(60000);
        httpRequestFactory.setConnectTimeout(5000);

        //BufferingClientHttpRequestFactory进行包装，解决流不能重复读取的问题
        BufferingClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(httpRequestFactory);

        //构建restTemplate
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(factory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        //打印日志
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggingRequestInterceptor(taskList));
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
}